//
//  TherapeuticCardController.m
//  yilutongxing
//
//  Created by T&J on 2017/11/15.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "TherapeuticCardController.h"
#import "RPMedicinePlan.h"
#import "RPMedicineSinglePlan.h"
#import "UITableView+EmptyData.h"
#import "TheraTitleCell.h"
#import "TheraMedicineTitleCell.h"
#import "TheraTakeplanCell.h"
#import "DataUtils.h"

#define TITLE_CELL_ID @"title_cell"
#define MEDCINE_TITLE_CELL_ID @"medcine_title_cell"
#define TAKE_PLAN_CELL_ID @"take_plan_cell"

@interface TherapeuticCardController()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, assign) CGRect frame;
@property(nonatomic, strong) RPMedicinePlan *plan;
@property(nonatomic, strong) NSMutableArray *arrayCache;//缓存整理好的服用时间和剂量数组
@property(nonatomic, assign) BOOL isLatest;//是否最新的，是则允许修改
@end

@implementation TherapeuticCardController

- (instancetype)initWithViewFrame:(CGRect)view_frame{
    self = [super init];
    if (self) {
        self.frame = view_frame;
    }
    return self;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:self.frame style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.layer.cornerRadius = 8;
        [_tableView setBackgroundView:nil];
        [_tableView setBackgroundColor:WHITE_COLOR];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        //[_tableView setAllowsSelection:NO];
        
        [_tableView registerNib:[UINib nibWithNibName:@"TheraTitleCell" bundle:nil] forCellReuseIdentifier:TITLE_CELL_ID];
        [_tableView registerNib:[UINib nibWithNibName:@"TheraMedicineTitleCell" bundle:nil] forCellReuseIdentifier:MEDCINE_TITLE_CELL_ID];
        [_tableView registerNib:[UINib nibWithNibName:@"TheraTakeplanCell" bundle:nil] forCellReuseIdentifier:TAKE_PLAN_CELL_ID];
    }
    return _tableView;
}

#pragma mark - TableView datasrouce
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    [tableView tableViewDisplayWithMsg:@"暂无内容" ifNecessaryForRowCount:self.plan.medicines.count];
    if (!self.plan) {
        return 0;
    }
    return self.plan.medicines.count + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger number = 2;
    if (section==0) {
        number = 1;
    }
    else {
        NSDictionary *dic = self.arrayCache[section-1];
        NSArray *timesArr = dic[@"timesArr"];
        number = timesArr.count + 1;
    }
    return number;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell;//
    if (indexPath.section==0) {
        TheraTitleCell *cell_t = [tableView dequeueReusableCellWithIdentifier:TITLE_CELL_ID forIndexPath:indexPath];
        cell_t.selectionStyle = UITableViewCellSelectionStyleNone;
        NSString *startime = @"无";
        if (self.plan.startTime) {
            startime = [self.plan.startTime stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
        }
        NSString *endtime = @"至今";
        if (self.plan.endTime) {
            endtime = [self.plan.endTime stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
        }
        NSString *time_title = [NSString stringWithFormat:@"%@-%@", startime, endtime];
        
        if (self.isLatest) {
            cell_t.btn_modify.hidden = NO;
            [cell_t.btn_modify addTarget:self action:@selector(modifyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        else {
            cell_t.btn_modify.hidden = YES;
        }
        if (self.plan.accept) {
            cell_t.btn_add.hidden = YES;
        }
        else {
            cell_t.btn_add.hidden = NO;
            [cell_t.btn_add addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        cell_t.title.text = time_title;
        cell = cell_t;
    }
    else {
        RPMedicineSinglePlan *sp = self.plan.medicines[indexPath.section-1];
        NSArray *timesArr = self.arrayCache[indexPath.section-1][@"timesArr"];
        NSArray *doseArr = self.arrayCache[indexPath.section-1][@"doseArr"];
        NSArray *unitArr = self.arrayCache[indexPath.section-1][@"unitArr"];
        if (indexPath.row==0) {
            TheraMedicineTitleCell *cell_t = (TheraMedicineTitleCell*)[tableView dequeueReusableCellWithIdentifier:MEDCINE_TITLE_CELL_ID forIndexPath:indexPath];
            cell_t.selectionStyle = UITableViewCellSelectionStyleNone;
            cell_t.medcine_name.text = sp.medicineName?sp.medicineName:(sp.medicine.name?sp.medicine.name:@"");
            cell_t.take_count.text = sp.frequency;
            cell = cell_t;
        }
        else {
            TheraTakeplanCell *cell_t = [tableView dequeueReusableCellWithIdentifier:TAKE_PLAN_CELL_ID forIndexPath:indexPath];
            cell_t.selectionStyle = UITableViewCellSelectionStyleNone;
            cell_t.time_index.text = [NSString stringWithFormat:@"第%@次", [DataUtils arabicConvert2Chinese:(indexPath.row-1)+1]];//注意-1又+1的意义
            cell_t.take_time.text = timesArr[indexPath.row-1];
            cell_t.dose.text = doseArr.count<=0?@"-":(doseArr.count<timesArr.count?doseArr[0]:doseArr[indexPath.row-1]);
            cell_t.unit.text = unitArr.count<=0?@"-":(unitArr.count<timesArr.count?unitArr[0]:unitArr[indexPath.row-1]);
            cell = cell_t;
        }
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    CGFloat height = 0.01;
    if (section>0) {
        height = 10;
    }
    return height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = 0.01;
    if (section>0) {
        height = 10;
    }
    return height;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 29;
    if (indexPath.section==0) {
        height = 44;
    }
    return height;
}

#pragma mark - 业务逻辑
- (void)setPlanData:(RPMedicinePlan *)plan forLatest:(BOOL)isLatest{
    self.plan = plan;
    self.isLatest = isLatest;
    [self.arrayCache removeAllObjects];
    for (RPMedicineSinglePlan *sp in self.plan.medicines) {
        NSArray *timesArr = [TherapeuticCardController str2Array:sp.times];
        NSArray *doseArr = [TherapeuticCardController str2Array:sp.dose];
        NSArray *unitArr = [TherapeuticCardController str2Array:sp.unit];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:timesArr forKey:@"timesArr"];
        [dic setObject:doseArr forKey:@"doseArr"];
        [dic setObject:unitArr forKey:@"unitArr"];
        [self.arrayCache addObject:dic];
    }
    [self.tableView reloadData];
}

#pragma mark - 辅助函数
+(NSMutableArray*)str2Array:(NSString*)timeStr{
    NSMutableArray *arr = [[timeStr componentsSeparatedByString:@","] mutableCopy];
    NSString *last = arr[arr.count-1];
    if ([last isEqualToString:@""]) {
        [arr removeLastObject];
    }
    return arr;
}

#pragma mark - 数据配置
- (NSMutableArray *)arrayCache{
    if (!_arrayCache) {
        _arrayCache = [NSMutableArray array];
    }
    return _arrayCache;
}

#pragma mark - UI事件
- (void)modifyBtnClick:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(OnModifyBtnClick)]) {
        [self.delegate OnModifyBtnClick];
    }
}
- (void)deleteBtnClick:(UIButton*)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(OnDeleteBtnClick)]) {
        [self.delegate OnDeleteBtnClick];
    }
}

@end
